﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using CMN.Models;
using CMN.Models.Interfaces;
using CMN.Entity;
using System.Web.Routing;
using CMN.Common;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using CMN.Controllers.Filters;
using System.Text;
namespace CMN.Controllers
{
    [ExceptionFilter]
    [LoggerFilter]
    [UserAuthorize]
    public class Sys_ErrorLogController : Controller
    {
        
        // 返回json字符串
        protected string returnJson = string.Empty;

        /// <summary>
        /// 转到View页面
        /// </summary>
        /// <returns></returns>
        public ViewResult Index()
        {
            return View("Index");//页面地址
        }

        /// <summary>
        /// 返回用户表列表
        /// </summary>
        /// <returns>json</returns>
        public string List(string actionId)
        {
            //返回json数组
          
            int pageSize = (int)Utils.GetQueryAndFormString("limit", this, 4, 1, DataType.Int);
            int pageIndex = (int)Utils.GetQueryAndFormString("page", this, 9, 1, DataType.Int);
            List<string> fileContents = GetFileTxtLogs(string.Concat(Utils.GetServerPath(), "manager\\log\\", actionId, ".log"));
            List<string> reFileContents = new List<string>();
            int start=fileContents.Count-(pageSize*(pageIndex-1));
            int length=(((pageSize*pageIndex)>fileContents.Count)?0:(fileContents.Count-(pageSize*pageIndex)));
            if(fileContents.Count<=pageSize)
            {
                start=fileContents.Count;
                length=0;
            }
            for (int i =start; i >length; i--)
            {
                if (i < fileContents.Count)
                {
                    
                    reFileContents.Add(fileContents[i]);

                }
            }
            StringBuilder sb = new StringBuilder();
            sb.Append(string.Concat("{totalPorperty:", fileContents.Count.ToString(), ",root:["));
            
            for (int i = 0; i < reFileContents.Count; i++)
            {
                sb.Append("{conent:");
                reFileContents[i] = reFileContents[i].Replace("\r\n", "<br />");
                reFileContents[i] = reFileContents[i].Replace("\n", "<br />");
                reFileContents[i] = reFileContents[i].Replace("\r", "<br />");
                reFileContents[i] = reFileContents[i].Replace(",", "，");
                reFileContents[i] = reFileContents[i].Replace("'", "‘");

                sb.Append(JsonConvert.SerializeObject( reFileContents[i]));
                if (i != (reFileContents.Count - 1))
                {
                    sb.Append("},");
                }
                else
                {
                    sb.Append("}");
                }
            }
            sb.Append("]}");
            return sb.ToString();
            
        }

        /// <summary>
        /// 读取文件日志
        /// </summary>
        /// <param name="FilePath">文件物理路径</param>
        /// <returns></returns>
        public static List<string> GetFileTxtLogs(string FilePath)
        {
            List<string> lst = new List<string>();
            string LogFileTxt = Utils.GetFileContent(FilePath, System.Text.Encoding.GetEncoding("gb2312"));

            string[] lines = LogFileTxt.Split(new string[] { "[$$$" }, StringSplitOptions.RemoveEmptyEntries);
            for (int i = 0; i < lines.Length; i++)
            {
                
                lst.Add(lines[i] );
            }
            return lst;

        }

        public string FileList()
        {
            List<String> fileList = Utils.GetDirFileList(string.Concat(Utils.GetServerPath(), "manager\\log"),"log");
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            for (int i = (fileList.Count-1); i >-1 ; i--)
            {

                sb.Append("{'text':'");
                sb.Append(fileList[i].Replace(".log",""));
                if (i != 0)
                {
                    sb.Append("',leaf:true,checked:false},");
                }
                else
                {
                    sb.Append("',leaf:true,checked:false}");
                }
            }
            sb.Append("]");
            return sb.ToString();
        }

        /// <summary>
        /// 查看用户表 
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Look(string actionId)
        {
           IDataService<Sys_UserEntity> Sys_UserSv = ServiceBuilder.BuildSys_UserService();
            int intId=Utils.StringToInt(actionId,0);
            Sys_UserEntity sys_user = Sys_UserSv.Look(intId);
            IsoDateTimeConverter jsDataConvert = new Newtonsoft.Json.Converters.IsoDateTimeConverter();
            jsDataConvert.DateTimeFormat = "yyyy-MM-dd";
            if (sys_user != null)
                returnJson = string.Concat("{success:true,data:", JsonConvert.SerializeObject(sys_user, Formatting.Indented, jsDataConvert), "}");
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 更新用户表
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Update(string actionId)
        {
            int intId = Utils.StringToInt(actionId,0);
            if (intId != 0)
            {
                IDataService<Sys_UserEntity> Sys_UserSv = ServiceBuilder.BuildSys_UserService();
                Sys_UserEntity sys_user = new Sys_UserEntity();
                sys_user.DataTable_Action = DataTableAction.Update;
                sys_user.UserID = intId;
                sys_user.U_LoginName = (String)Utils.GetQueryAndFormString("U_LoginName", this, 20,  1 , DataType.CharAndNum);
                sys_user.U_Password = (String)Utils.GetQueryAndFormString("U_Password", this, 32,  1 , DataType.Str);
                string strNewPwd=(String)Utils.GetQueryAndFormString("U_Password2", this, 32,  0 , DataType.CharAndNum);
                if (!string.IsNullOrEmpty(strNewPwd))
                {
                    sys_user.U_Password = Utils.Md5(strNewPwd, 32);
                }
                sys_user.U_CName = (String)Utils.GetQueryAndFormString("U_CName", this, 20,  0, DataType.Str);
                sys_user.U_EName = (String)Utils.GetQueryAndFormString("U_EName", this, 50,  0, DataType.Str);
                sys_user.U_GroupID = (Int32)Utils.GetQueryAndFormString("U_GroupID", this, 10,  1 , DataType.Int);
                sys_user.U_Email = (String)Utils.GetQueryAndFormString("U_Email", this, 100,  0, DataType.Str);
                sys_user.U_Type = (Byte)Utils.GetQueryAndFormString("U_Type", this, 3,  1 , DataType.Byte);
                sys_user.U_Status = (Byte)Utils.GetQueryAndFormString("U_Status", this, 3,  1 , DataType.Byte);
                sys_user.U_Licence = (String)Utils.GetQueryAndFormString("U_Licence", this, 30,  0, DataType.Str);
                sys_user.U_Mac = (String)Utils.GetQueryAndFormString("U_Mac", this, 50,  0, DataType.Str);
                sys_user.U_Remark = (String)Utils.GetQueryAndFormString("U_Remark", this, 200,  0, DataType.Str);
                sys_user.U_IDCard = (String)Utils.GetQueryAndFormString("U_IDCard", this, 30,  0, DataType.Str);
                sys_user.U_Sex = (Byte)Utils.GetQueryAndFormString("U_Sex", this, 3,  0, DataType.Byte);
                sys_user.U_BirthDay = (DateTime?)Utils.GetQueryAndFormString("U_BirthDay", this, 23,  0, DataType.Dat);
                sys_user.U_MobileNo = (String)Utils.GetQueryAndFormString("U_MobileNo", this, 15,  0, DataType.Str);
                sys_user.U_UserNO = (String)Utils.GetQueryAndFormString("U_UserNO", this, 20,  0, DataType.Str);
                sys_user.U_WorkStartDate = (DateTime?)Utils.GetQueryAndFormString("U_WorkStartDate", this, 23,  0, DataType.Dat);
                sys_user.U_WorkEndDate = (DateTime?)Utils.GetQueryAndFormString("U_WorkEndDate", this, 23,  0, DataType.Dat);
                sys_user.U_CompanyMail = (String)Utils.GetQueryAndFormString("U_CompanyMail", this, 255,  0, DataType.Str);
                sys_user.U_Title = (Int32)Utils.GetQueryAndFormString("U_Title", this, 10,  0, DataType.Int);
                sys_user.U_Extension = (String)Utils.GetQueryAndFormString("U_Extension", this, 10,  0, DataType.Str);
                sys_user.U_HomeTel = (String)Utils.GetQueryAndFormString("U_HomeTel", this, 20,  0, DataType.Str);
                sys_user.U_PhotoUrl = (String)Utils.GetQueryAndFormString("U_PhotoUrl", this, 255,  0, DataType.Str);
                sys_user.U_DateTime = (DateTime?)Utils.GetQueryAndFormString("U_DateTime", this, 23,  0, DataType.Dat);
                sys_user.U_LastIP = (String)Utils.GetQueryAndFormString("U_LastIP", this, 15,  0, DataType.Str);
                sys_user.U_LastDateTime = (DateTime?)Utils.GetQueryAndFormString("U_LastDateTime", this, 23,  0, DataType.Dat);
                sys_user.U_ExtendField = (String)Utils.GetQueryAndFormString("U_ExtendField", this, 2147483647,  0, DataType.Str);

                if (Sys_UserSv.Update(sys_user) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";
            }
            else
            {
                returnJson = "{success:'false'}";
            }
           
            return returnJson;
        }

        /// <summary>
        /// 新增用户表
        /// </summary>
        /// <returns>json</returns>
        public string Insert()
        {
            Sys_UserEntity sys_user = new Sys_UserEntity();
            IDataService<Sys_UserEntity> Sys_UserSv = ServiceBuilder.BuildSys_UserService();
            sys_user.DataTable_Action = DataTableAction.Insert;
            sys_user.U_LoginName = (String)Utils.GetQueryAndFormString("U_LoginName", this, 20,  1 , DataType.CharAndNum);
            QueryParam qp = new QueryParam();
            qp.Where = " U_LoginName='" + sys_user.U_LoginName + "'";
            qp.PageSize = 1;
            int recourdNum = 0;
            if (Sys_UserSv.List(qp, out recourdNum).Count > 0)
            {
                return returnJson = "{success:'false',message:'已存在的用户名'}";
            }
            sys_user.U_Password = (String)Utils.GetQueryAndFormString("U_Password", this, 32,  1 , DataType.Str);
            sys_user.U_CName = (String)Utils.GetQueryAndFormString("U_CName", this, 20,  0, DataType.Str);
            sys_user.U_EName = (String)Utils.GetQueryAndFormString("U_EName", this, 50,  0, DataType.Str);
            sys_user.U_GroupID = (Int32)Utils.GetQueryAndFormString("U_GroupID", this, 10,  1 , DataType.Int);
            sys_user.U_Email = (String)Utils.GetQueryAndFormString("U_Email", this, 100,  0, DataType.Str);
            sys_user.U_Type = (Byte)Utils.GetQueryAndFormString("U_Type", this, 3,  1 , DataType.Byte);
            sys_user.U_Status = (Byte)Utils.GetQueryAndFormString("U_Status", this, 3,  1 , DataType.Byte);
            sys_user.U_Licence = (String)Utils.GetQueryAndFormString("U_Licence", this, 30,  0, DataType.Str);
            sys_user.U_Mac = (String)Utils.GetQueryAndFormString("U_Mac", this, 50,  0, DataType.Str);
            sys_user.U_Remark = (String)Utils.GetQueryAndFormString("U_Remark", this, 200,  0, DataType.Str);
            sys_user.U_IDCard = (String)Utils.GetQueryAndFormString("U_IDCard", this, 30,  0, DataType.Str);
            sys_user.U_Sex = (Byte)Utils.GetQueryAndFormString("U_Sex", this, 3,  0, DataType.Byte);
            sys_user.U_BirthDay = (DateTime?)Utils.GetQueryAndFormString("U_BirthDay", this, 23,  0, DataType.Dat);
            sys_user.U_MobileNo = (String)Utils.GetQueryAndFormString("U_MobileNo", this, 15,  0, DataType.Str);
            sys_user.U_UserNO = (String)Utils.GetQueryAndFormString("U_UserNO", this, 20,  0, DataType.Str);
            sys_user.U_WorkStartDate = (DateTime?)Utils.GetQueryAndFormString("U_WorkStartDate", this, 23,  0, DataType.Dat);
            sys_user.U_WorkEndDate = (DateTime?)Utils.GetQueryAndFormString("U_WorkEndDate", this, 23,  0, DataType.Dat);
            sys_user.U_CompanyMail = (String)Utils.GetQueryAndFormString("U_CompanyMail", this, 255,  0, DataType.Str);
            sys_user.U_Title = (Int32)Utils.GetQueryAndFormString("U_Title", this, 10,  0, DataType.Int);
            sys_user.U_Extension = (String)Utils.GetQueryAndFormString("U_Extension", this, 10,  0, DataType.Str);
            sys_user.U_HomeTel = (String)Utils.GetQueryAndFormString("U_HomeTel", this, 20,  0, DataType.Str);
            sys_user.U_PhotoUrl = (String)Utils.GetQueryAndFormString("U_PhotoUrl", this, 255,  0, DataType.Str);
            sys_user.U_DateTime = (DateTime?)Utils.GetQueryAndFormString("U_DateTime", this, 23,  0, DataType.Dat);
            sys_user.U_LastIP = (String)Utils.GetQueryAndFormString("U_LastIP", this, 15,  0, DataType.Str);
            sys_user.U_LastDateTime = (DateTime?)Utils.GetQueryAndFormString("U_LastDateTime", this, 23,  0, DataType.Dat);
            sys_user.U_ExtendField = (String)Utils.GetQueryAndFormString("U_ExtendField", this, 2147483647,  0, DataType.Str);

            if (Sys_UserSv.Insert(sys_user) == "")
            {
                returnJson = "{success:'true'}";
            }
            else
                returnJson = "{success:'false'}";
            return returnJson;
        }

        /// <summary>
        /// 删除用户表
        /// </summary>
        /// <param name="id"></param>
        /// <returns>json</returns>
        public string Delete(string actionId)
        {
            string intId = actionId;
            if (!string.IsNullOrEmpty(intId))
            {
                List<string> str = Utils.StringToArray(intId, ',', false);
                string path=string.Concat(Utils.GetServerPath(), "manager\\log");
                if (str.Count < 1)
                {
                  return   returnJson = "{success:'false',message:'删除文件名为空'}";
                }
                try
                {
                    for (int i = 0; i < str.Count; i++)
                    {
                        string fileFullPath = string.Concat(path, "\\", str[i], ".log");
                        if (Utils.IsExistsFile(fileFullPath))
                        {
                            Utils.DeleteFile(fileFullPath);
                        }
                    }

                    returnJson = "{success:'true'}";
                }
                catch (Exception ex)
                {
                    returnJson = string.Concat("{success:'false',message:'", ex.Message, "'}");
                }
               
            }
            else
            {
                returnJson = "{success:'false',message:'删除文件名为空'}";
            }
            return returnJson;
        }

        /// <summary>
        /// 批量删除用户表
        /// </summary>
        /// <param name="idList">id列表 234_4_5</param>
        /// <returns>json</returns>
        public string DeleteList(string actionId)
        {
            Common.RegExpression.NumAndBarRegExpression regex = new CMN.Common.RegExpression.NumAndBarRegExpression();
            if (regex.IsMatch(actionId))
            {

                IDataService<Sys_UserEntity> Sys_UserSv = ServiceBuilder.BuildSys_UserService();
                if (Sys_UserSv.DeleteList(actionId) == "")
                {
                    returnJson = "{success:'true'}";
                }
                else
                    returnJson = "{success:'false'}";

            }
            else
            {
                returnJson = "{success:'false',message:'参数类型不正确'}";
            }
            return returnJson;
        }

    }
}
